#pragma once

#include <cassert>

//Singleton class is from the following site:
//http://www.drizzle.com/~scottb/publish/gpgems1_singleton.htm
//
//The following modifications have been made:
// - used static_cast method described here: 
//http://www.drizzle.com/~scottb/publish/gpgems1_singleton_notes.htm
//
// Based on http://www.drizzle.com/~scottb/publish/gpgems1_singleton.htm

//! To make a class into a singleton publically extend this (T = the class to extend).
/// Use T::getSingleton() or T::getSingletonPtr() to get the object. It is the
/// users responsibility to create T somewhere exactly once within their application.
/// 
/// Example usage:
///
///    MyClass instance;
///
///    // can be called from anywhere as long as instance is still alive
///
///    MyClass::getSingleton().doSomething(); 
template <typename T> class Singleton
{
    static T* ms_Singleton;
public:

    //! Asserts if the extending class is created more than once
    Singleton( void )
    {
    assert( !ms_Singleton && 
        "A Singleton<T> extending class has been initialized more than once.");
    ms_Singleton = static_cast <T*> (this);
    }

    //! Singleton no longer is available if the instance is destroyed
    ~Singleton( void )
    {  
    // To be destructed the singleton must have been made once already
    assert( ms_Singleton ); 
    ms_Singleton = 0;  
    }

    //! Get reference to T
    static T& getSingleton( void )
    {  
    assert( ms_Singleton && "The singleton hasn't been instantiated anywhere yet");  
    return ( *ms_Singleton ); 
    }

    //! Get pointer to T
    static T* getSingletonPtr( void )
    {  return ( ms_Singleton );  }
};

template <typename T> T* Singleton <T>::ms_Singleton = 0;




